<template>
  <div class="common stock-inner">
    <div class="common-top flex flex-align-center">
      <span class="tips">{{modeType=='PRODUCT'?'商品':'原料'}}入库</span>
      <div class="search-box" style="z-index:999">
        <el-input class="input-box" placeholder="请输入名称" prefix-icon="el-icon-search" v-model="keyWords" @blur="blurSearch">
        </el-input>
        <ul class="ul-box" v-if="searchArr.length">
          <li v-for="item in searchArr" v-text="item.name" @click="getSearchItem(item)"></li>
        </ul>
      </div>
      <span style="color:#ff0048;border-bottom:1px solid #ff0048;margin-left: 20px;cursor:pointer;" @click.stop="$router.push({path:'/Stock_Inner_All',query:{queryModeType:modeType}})">全部{{modeType=='PRODUCT'?'商品':'原料'}}模式入库</span>
      <div class="change-stock-btn mode">
				<span>商品</span>
				<span :class="modeType=='PRODUCT'?'change-btn':'change-btn right-btn'" @click.stop="changeModeType">
					<i @click.stop=""></i>
				</span>
				<span>原料</span>
			</div>
      <!-- <div class="search-btn" style="margin-left:80px;" @click="getBatchData">
				全部商品
			</div> -->
    </div>
    <div class="content-box">
      <div class="content" v-if="modeType=='PRODUCT'">
        <div class="titleTable">
          <table @click.stop="doShowAddInp">
            <tr>
              <th style="width: 8%">序号</th>
              <th style="width:12%">商品名称</th>
              <th style="width:12%">仓库原有件数</th>
              <!-- <th style="width:12%">原有散装个数(个)</th> -->
              <th style="width:10%">规格(个/件)</th>
              <th style="width:12%">每件进价(元/件)</th>
              <th style="width:10%">入库件数</th>
              <!-- <th style="width:12%">入库个数(个)</th> -->
              <th style="width:12%">操作</th>
            </tr>
          </table>
        </div>
        <div class="scrollBox" @click.stop="doShowAddInp">
          <div class="scroll" :style="{'height':homeArr.length*10+'%'}">
            <table class="conTable" @click.stop="doShowAddInp">
              <tr v-for="(item,ind) in homeArr" class="capacity-tr">
                <td style="width:8%" v-text="ind+1"></td>
                <td style="width:12%" v-text="item.name" :title="item.name"></td>
                <td style="width:12%" v-text="item.quantity" :title="item.quantity"></td>
                <!-- <td style="width:12%" v-text="item.stockQuantityRatio==0?'-':parseInt(item.warehouseQuantity/item.stockQuantityRatio)"></td> -->
                <!-- <td style="width:12%" v-text="item.stockQuantityRatio==0?item.warehouseQuantity:(item.warehouseQuantity%item.stockQuantityRatio)"></td> -->
                <!--  -->
                <!-- <td style="width:10%">
                                	<span v-if="item.isStock" class="table-input">
										<input type="text" maxlength="4" v-model="item.stockQuantityRatio" @keyup.enter="modify(item,ind,'stock')">
										<span @click="modify(item,ind,'stock')" class="sure-btn">确定</span>
									</span>
									<span v-else><span v-text="item.stockQuantityRatio"></span></span>
                                </td> -->
                <!-- <td style="width:10%" class="standard">
									<div  @click.stop="showStandard(ind,item)">
										<div><span style="padding-right:5px;cursor:pointer;" v-text="item.capacity"></span><i  :class="doShowStandard&&ind===nowInd?'iconfont icon-jiantou trans':'iconfont icon-jiantou'"></i></div>
										<ul ref="standardUlRef" :class="doShowStandard&&ind===nowInd?'standard-ul show-ul':'standard-ul'">
											<li @click.stop="showNowStandard(capacityItem)" v-for="(capacityItem,capacityIndex) in capacityArr" :key="capacityIndex"><span class="standard-count">{{capacityItem.capacity}}</span><i @click.stop="delStandard(capacityItem,item)" class="iconfont icon-shanchu"></i></li>
											<li class="plus-inp" v-if="showAddInp" @click.stop=""><input type="text" v-model="standard" v-focus autofocus="autofocus" placeholder="请输入规格" @keyup.enter="addStandard(item)"><i @click="addStandard(item)" class="iconfont icon-duigou"></i></li>
											<li class="plus-li" @click.stop="showAddInp=true"><span class="plus" >+</span></li>
										</ul>
									</div>
                                </td> -->
                <td style="width:10%" class="capacity" title="切换规格" @click.stop="showStandard(ind,item)">
                  <div class="standard-wrap">
                    <div style="padding:5px;">
                      <span class="capacity-count">{{item.capacity}}</span>
                      <i :class="doShowStandard&&ind===nowInd?'iconfont icon-jiantou trans':'iconfont icon-jiantou'"></i>
                    </div>
                    <div :class="doShowStandard&&ind===nowInd?'ul-wrap show-ul':'ul-wrap'" :style="showAddInp?'height:150px;':'height:110px;'">
                      <div class="ul-inner-wrap">
                        <ul>
                          <li @click.stop="showNowStandard(capacityItem)" v-for="(capacityItem,capacityIndex) in capacityArr" :key="capacityIndex">
                            <span class="standard-count">{{capacityItem.capacity}}</span>
                            <i @click.stop="delStandard(capacityItem,item)" class="del-capacity iconfont icon-shanchu"></i>
                          </li>
                        </ul>
                      </div>
                      <div class="plus-inp" :style='showAddInp&&ind===nowInd?"visibility: visible":"visibility: hidden"' @click.stop="">
                        <input type="text" v-model="standard" v-focus autofocus="autofocus" placeholder="请输入规格" @keyup.enter="addStandard(item)">
                        <i @click="addStandard(item)" class="iconfont icon-duigou"></i>
                      </div>
                      <div class="plus-li" @click.stop="showAddInp=true">
                        <span class="plus">+</span>
                      </div>
                    </div>
                  </div>
                </td>
                <!--  -->
                <td style="width:12%">
                  <span v-if="item.isPrice" class="table-input">
                    <input type="text" maxlength="7" v-model="item.purchasePrice" @keyup.enter="modify(item,ind,'price')" class="inputPrice">
                    <span @click="modify(item,ind,'price')" class="sure-btn">确定</span>
                  </span>
                  <span v-else>
                    <span v-text="item.purchasePrice"></span>
                    <i class="iconfont icon-bianji" @click="homeArr[ind].isPrice=true"></i>
                  </span>
                </td>
                <td style="width:10%">
                  <!-- onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')" -->
                  <span class="table-input"><input type="text" maxlength="5" v-model="item.whole" onfocus="this.select()"></span>
                </td>
                <!-- <td style="width:12%">
                                	<span class="table-input"><input type="text" maxlength="4" v-model="item.single" onfocus="this.select()"></span>
                                </td> -->
                <td style="width:12%">
                  <span class="btn" @click="del(item,ind)">删除</span>
                </td>
              </tr>
            </table>
          </div>
        </div>
        <div class="content-footer clearfix">
          <div class="right flex flex-align-center" style="height:100%;">
            <div class="footer-btn sure" @click="willUp">
              下一步
            </div>
          </div>
        </div>
      </div>
      <!--  -->
      <div class="content" v-if="modeType=='MATERIAL'">
        <div class="titleTable">
          <table @click.stop="doShowAddInp">
            <tr>
              <th style="width: 8%">序号</th>
              <th style="width:12%">原料名称</th>
              <th style="width:12%">仓库原有数</th>
              <th style="width:10%">规格</th>
              <th style="width:10%">单位</th>
              <th style="width:12%">进价</th>
              <th style="width:10%">入库数</th>
              <th style="width:12%">操作</th>
            </tr>
          </table>
        </div>
        <div class="scrollBox" @click.stop="doShowAddInp">
          <div class="scroll" :style="{'height':homeArr.length*10+'%'}">
            <table class="conTable" @click.stop="doShowAddInp">
              <tr v-for="(item,ind) in homeArr" class="capacity-tr">
                <td style="width:8%" v-text="ind+1"></td>
                <td style="width:12%" v-text="item.name" :title="item.name"></td>
                <td style="width:12%" v-text="item.quantity" :title="item.quantity"></td>
                <td style="width:10%" class="capacity" title="切换规格" @click.stop="showStandard(ind,item)">
                  <div class="standard-wrap">
                    <div style="padding:5px;">
                      <span class="capacity-count">{{item.capacity}}</span>
                      <i :class="doShowStandard&&ind===nowInd?'iconfont icon-jiantou trans':'iconfont icon-jiantou'"></i>
                    </div>
                    <div :class="doShowStandard&&ind===nowInd?'ul-wrap show-ul':'ul-wrap'" :style="showAddInp?'height:150px;':'height:110px;'">
                      <div class="ul-inner-wrap">
                        <ul>
                          <li @click.stop="showNowStandard(capacityItem)" v-for="(capacityItem,capacityIndex) in capacityArr" :key="capacityIndex">
                            <span class="standard-count">{{capacityItem.capacity}}</span>
                            <i @click.stop="delStandard(capacityItem,item)" class="del-capacity iconfont icon-shanchu"></i>
                          </li>
                        </ul>
                      </div>
                      <div class="plus-inp" :style='showAddInp&&ind===nowInd?"visibility: visible":"visibility: hidden"' @click.stop="">
                        <input type="text" v-model="standard" v-focus autofocus="autofocus" placeholder="请输入规格" @keyup.enter="addStandard(item)">
                        <i @click="addStandard(item)" class="iconfont icon-duigou"></i>
                      </div>
                      <div class="plus-li" @click.stop="showAddInp=true">
                        <span class="plus">+</span>
                      </div>
                    </div>
                  </div>
                </td>
                <td style="width:12%" v-text="item.unitName" :title="item.unitName"></td>
                <!--  -->
                <td style="width:12%">
                  <span v-if="item.isPrice" class="table-input">
                    <input type="text" maxlength="7" v-model="item.purchasePrice" @keyup.enter="modify(item,ind,'price')" class="inputPrice">
                    <span @click="modify(item,ind,'price')" class="sure-btn">确定</span>
                  </span>
                  <span v-else>
                    <span v-text="item.purchasePrice"></span>
                    <i class="iconfont icon-bianji" @click="homeArr[ind].isPrice=true"></i>
                  </span>
                </td>
                <td style="width:10%">
                  <span class="table-input"><input type="text" maxlength="5" v-model="item.whole" onfocus="this.select()"></span>
                </td>
                <td style="width:12%">
                  <span class="btn" @click="del(item,ind)">删除</span>
                </td>
              </tr>
            </table>
          </div>
        </div>
        <div class="content-footer clearfix">
          <div class="right flex flex-align-center" style="height:100%;">
            <div class="footer-btn sure" @click="willUp">
              下一步
            </div>
          </div>
        </div>
      </div>
      <!--  -->
    </div>

    <div class="dialog-box" v-if="dialogBtn" @click="dialogBtn=false">
      <div class="dialog position-middle-center" @click.stop="">
        <span class="close-btn" @click="dialogBtn=false">
          <i class="iconfont icon-close-b"></i>
        </span>
        <div class="dialog-title">确认入库</div>
        <div class="dialog-content" style="margin-top:20px;">
          <div class="dialog-content-item-center">
            <span>入库项总共
              <span class="big-num" v-text="billData.kind"> </span>种</span>
          </div>
          <!-- <div class="dialog-content-item clearfix select-box">
            <span>总额</span>
            <el-input class="input-box" placeholder="本次入库的总金额，如有需要请填写。" v-model="billData.totalAmount">
            </el-input>
          </div> -->
          <div class="dialog-content-item clearfix select-box">
            <span>原因</span>
            <el-select v-model="billData.typeValue" placeholder="请选择入库原因" class="select">
              <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="dialog-content-item clearfix select-box">
            <span>备注</span>
            <el-input class="input-box" placeholder="如有需求，请填写备注" v-model="billData.notes">
            </el-input>
          </div>
          <!-- <div class="dialog-content-item clearfix imgfile-box">
						<span class="left">单据</span>
						<div class="img left">
							<img :src="billData.imgUrl" alt="">
							<input type="file" accept=".png,.jpg,.jpeg" @change="coverImg($event)" class="pcImgFile" title="选择图片">
						</div>
						<div class="left right-notes">
							<p>支持JPG、JPEG、PNG格式单张大小不超过5M</p>
							<p class="status" v-if="billData.imgUrl">上传成功</p>
						</div>
					</div> -->
          <!-- <div class="dialog-content-item clearfix dialog-content-print">
						<span>打印</span>
						<input type="checkbox" class="isPrint" v-model="billData.isPrint">
						<input type="text" class="printNum" v-model="billData.printNum"  v-if="billData.isPrint">	
					</div> -->
        </div>
        <div class="dialog-footer">
          <div class="footer-btn cancle" @click="dialogBtn=false">取消</div>
          <div class="footer-btn sure" @click="stockUp">确定</div>
        </div>
      </div>
    </div>
    <div style="display:none;">
      <div id="print">
        <h1 style="text-align:center;font-size:18px;">欢迎使用火星捕手</h1>
        <p style="text-align:center;font-size:16px;">仓库入库小票</p>
        <div>
          <span>店铺名:</span>
          <span v-text="store.storeName"></span>
        </div>
        <div>
          <span>操作员:</span>
          <span v-text="store.employeeName"></span>
        </div>
        <div>
          <span>打印时间:</span>
          <span>{{new Date() | numberToAllDate('')}}</span>
        </div>
        <div>
          <span>总金额:</span>
          <span v-text="billData.totalAmount"></span>
        </div>
        <div>
          <span>入库原因:</span>
          <span v-text="sourceType[billData.typeValue]"></span>
        </div>
        <div>
          <span>备注:</span>
          <span v-text="billData.notes"></span>
        </div>
        <div v-for="(item,idx) in homeArr" style="margin-top:10px;border:1px solid #444">
          <table style="width:100%;border-collapse: collapse;table-layout:fixed;font-size:12px;">
            <tr>
              <td style="width:50%;overflow:hidden;white-space:nowrap;">
                <span>名称:</span>
                <span v-text="item.name"></span>
              </td>
              <td style="width:50%;">
                <span>规格(个/件):</span>
                <span v-text="item.stockQuantityRatio"></span>
              </td>
            </tr>
            <tr>
              <td style="width:50%;">
                <span>入库件数:</span>
                <span v-text="item.whole"></span>
              </td>
              <td style="width:50%;">
                <span>入库个数:</span>
                <span v-text="item.single"></span>
              </td>
            </tr>
          </table>
        </div>
      </div>
    </div>
    <img-crop v-if="showCrop" :oldImg="oldImgBase64" :curCropW="curCropW" :curCropH="curCropH" :storeId="storeId" @closeImgCrop="showCrop=false" @getCropImgBase="getCropImgBase"></img-crop>

    <div id="mask" v-if="doShowFirst" @click.stop="doShowFirst=false">
      <div class="first-in-add-cap" @click.stop="">
        <div class="goods-name-tit">名称:{{goodsName}}</div>
        <!-- <div class="search-box" style="z-index:999">
					<el-input
						class="input-box"
						placeholder="请输入商品名称"
						prefix-icon="el-icon-search"
						@blur="blurSearch"
						v-model="keyWordsForFirstCap"
						@keyup.enter.native="saveFirstCap"
						>
					</el-input>
					<ul class="ul-box" v-if="searchArrForFirst.length">
						<li v-for="item in searchArrForFirst" v-text="item.name" @click="getSearchItemForFirst(item)"></li>
					</ul>
				</div> -->
        <span class="first-cap">输入规格:</span>
        <div class="search-box">
          <el-input class="input-box" placeholder="请输入规格，如：10" prefix-icon="" v-model="firstCap" @keyup.enter.native="saveFirstCap">
          </el-input>
        </div>
        <span class="first-cap">输入单价:</span>
        <div class="search-box">
          <el-input class="input-box" placeholder="请输入进价" prefix-icon="" v-model="CapPurMoney" @keyup.enter.native="saveFirstCap">
          </el-input>
        </div>
        <div class="saveFirst">
          <button @click="saveFirstCap">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import imgCrop from "@/components/imgCrop/imgCrop.vue";
import {API_BASE_URL} from "./../../../urlConfig/index";
export default {
  components: { imgCrop },
  props: ["storeId", "store"],
  data() {
    return {
      modeType:"PRODUCT",
      typeOptions: [
        // {value: 'CHECK_IN',label: '盘点入库'},
        // {value: 'REFUND_IN',label: '退单入库'},
        { value: "PURCHASE_IN", label: "采购入库" },
        { value: "ALLOCATION_IN", label: "调拨入库" },
        { value: "INNER_IN", label: "吧台退回" }
      ],
      sourceType: {
        PURCHASE: "采购入库",
        ALLOCATION: "店铺调拨",
        CHECK_IN: "盘点入库",
        STOCK_OUT_ONE: "吧台到仓库",
        CHECK_OUT: "盘点出库",
        STORAGE: "仓储（仓库至吧台）",
        REFUND: "退单入库",
        SALES: "销售出库",
        REFUND_OUT: "退货出库",
        DECLINE: "吧台下架"
      },
      keyWords: "",
      currentPage: 1,
      pageSize: 10,
      total: 516,
      dialogBtn: false,
      options: [],
      typeId: "",

      coverImgMaxSize: 5 * 1024 * 1024, // 图片最大字节数
      oldImgBase64: "", // 原图base64
      showCrop: false, // 控制图片裁剪显示隐藏
      curCropW: 600, // 裁剪宽度
      curCropH: 600, // 裁剪高度

      searchArr: [], //搜索的商品列表
      homeArr: [], //首页商品列表
      billData: {
        typeValue: "PURCHASE_IN", //默认采购入库
        notes: "",
        totalAmount: "", //用户手动输入的总金额
        imgUrl: "",
        kind: 0,
        printNum: 1,
        isPrint: false
      },
      preventBtn: true,
      showAddInp: false, //是否显示输入框
      doShowStandard: false, //是否显示规格
      nowInd: 0, //当前选择的规格索引
      standard: "", //添加的规格名字
      capacityArr: [], //规格列表
      searchItem: {}, //所点击的搜索结果列表对象
      // deleteItemArr:[]//所删除的项目
      searchArrForFirst: [], //初次添加规格
      doShowFirst: false,
      CapPurMoney: "", //添加规格时所需要的单价,
      searchItemForFirst: null, //第一次添加规格时所选的搜索商品项
      firstCap: "",
      modifyCapItemForDel: null, //存储删除规格项的相关信息
      modifyCapItemForAdd: null,
      firstCapItem:null,//存储规格项,
      isDel:false
    };
  },
  watch: {
    keyWords(val) {
      this.searchArr = [];
      if (!val) {
        return;
      }
      // 搜索
      if(this.modeType == "MATERIAL"){
        this.$http({
          url: "query/list",
          method: "GET",
          params: {
            storeId: this.storeId,
            name: val
          }
        }).then(res => {
          this.searchArr = res.data;
        });
      }else{
        this.$http({
          url: "search",
          method: "GET",
          params: {
            storeId: this.storeId,
            q: val
          }
        }).then(res => {
          this.searchArr = res.data;
        });
      }
    },
    keyWordsForFirstCap(val) {
      if (this.searchItemForFirst) {
        if (val === this.searchItemForFirst.name) {
          return;
        }
      }
      this.searchArrForFirst = [];
      if (!val) {
        if (this.isBarStock) {
          this.getBarData(this.currentPageForBar - 1);
        } else {
          this.getHomeData(this.currentPage - 1);
          //隐藏规格相关
          this.doShowAddInp();
        }
        return;
      }
      // 搜索
      this.$http({
        url: "search",
        method: "GET",
        params: {
          storeId: this.storeId,
          q: val
        }
      }).then(res => {
        this.searchArrForFirst = res.data;
      });
    },
    doShowFirst(val) {
      this.searchItemForFirst = null;
      this.CapPurMoney = "";
      this.firstCap = "";
      this.keyWordsForFirstCap = "";
      this.doShowAddInp();
    }
  },
  computed: {
    goodsName:function(){
      if(this.searchItem){
        return this.searchItem.name.length>5?this.searchItem.name.substring(0,5)+'...':this.searchItem.name;
      }else if(this.firstCapItem){
         return this.firstCapItem.name.length>5?this.firstCapItem.name.substring(0,5)+'...':this.firstCapItem.name;
      }
    }
  },
  methods: {
    changeModeType(){
      this.homeArr = [];
      this.modeType == "PRODUCT"?this.modeType="MATERIAL":this.modeType="PRODUCT";
    },
    // 
    saveFirstCap() {
      //
      if(this.searchItem){
        this.firstCapItem = this.searchItem;
      }else if(this.modifyCapItemForDel){
        this.firstCapItem = {
          id:this.modifyCapItemForDel.productId,
          name:this.modifyCapItemForDel.name
        }
        // this.firstCapItem = this.modifyCapItemForDel;
      }
      //   console.log("l");
      if (!/^(0|[1-9][0-9]{0,9})(\.[0-9]{1,2})?$/.test(this.CapPurMoney)) {
        this.$message({
          showClose: true,
          message: "价格输入有误",
          type: "error",
          duration: 2000
        });
        return;
      }
      if (parseInt(this.firstCap) > 999) {
        this.$message({
          message: "规格输入过大",
          type: "error",
          duration: 2000
        });
        return;
      }
      // if (parseInt(this.firstCap) < 2) {
      //   this.$message({
      //     showClose: true,
      //     message: "商品规格必须大于1，否则请直接到菜单“吧台”中，进行“上架操作”。",
      //     type: "error",
      //     duration: 3000
      //   });
      //   return;
      // }
      if (!/^[1-9][0-9]*$/.test(this.firstCap)) {
        // if(this.standard === '0'){
        // 	doAddStandard();
        // 	return;
        // }
        this.$message({
          showClose: true,
          message: "输入规格有误",
          type: "error",
          duration: 2000
        });
        return;
      }
      console.log(this.modeType)
      this.$http({
        url: "add-indexCa",
        method: "POST",
        data: {
          productId: this.firstCapItem.id,
          productName: this.firstCapItem.name,
          capacity: this.firstCap,
          storeId: this.storeId,
          mold: this.modeType,
          purchasePrice: this.CapPurMoney,
          unitId:this.modeType=="MATERIAL"?this.firstCapItem.unitId:undefined
        }
      }).then(res => {
        console.log(res);
        let data = res.data;
        // this.homeArr = [];
        //
        this.homeArr.map((item, index) => {
          if (item.productId === data.productId) {
          }
        });
        //
        this.homeArr.push(data.data);
        this.doShowFirst = false;
        this.$message({
          showClose: true,
          message: data.msg,
          type: "success",
          duration: 2000
        });
        this.searchItem = null;
      });
    },
    getSearchItemForFirst(item) {
      this.searchItemForFirst = item;
      this.keyWordsForFirstCap = item.name;
      this.searchArrForFirst = [];
      console.log(item);
    },
    //初始界面添加规格
    firstAddCap() {
      this.doShowFirst = true;
    },
    blurSearch() {
      setTimeout(() => {
        this.searchArr = [];
      }, 800);
    },
    // 改变当前商品规格
    showNowStandard(item) {
      this.$http({
        url: "get-invCa",
        method: "GET",
        params: {
          invId: item.id,
          cap: item.capacity
        }
      }).then(res => {
        this.homeArr.map((ele, index) => {
          if (ele.productId === res.data.productId) {
            res.data.isPrice = false;
            res.data.whole = 0;
            this.homeArr.splice(index, 1, res.data);
          }
        });
      });
    },
    // 是否显示规格输入框
    doShowAddInp() {
      this.showAddInp = false;
      this.doShowStandard = false;
    },
    // 是否显示规格
    showStandard(index, item) {
      this.nowInd = index;
      this.doShowStandard = !this.doShowStandard;
      this.showAddInp = false;
      // this.doShowStandard?this.showAddInp = false:this.showAddInp=true;
      // 调取规格列表
      if (this.doShowStandard) {
        this.getStandardList(item);
      }
    },
    // 获取规格列表
    getStandardList(item) {
      this.$http({
        url: "/find-capacity",
        method: "GET",
        params: {
          productId: item.productId,
          storeId: this.storeId
        }
      }).then(res => {
        this.capacityArr = res.data;
      });
    },
    // 添加规格
    addStandard(item) {
      this.modifyCapItemForAdd = item;
      console.log(this.standard);
      console.log(item);
      console.log(this.searchItemForFirst)
      if (parseInt(this.standard) > 999) {
        this.$message({
          message: "规格输入过大",
          type: "error",
          showClose: true,
          duration: 2000
        });
        return;
      }
      // if (parseInt(this.standard) < 2) {
      //   this.$message({
      //     showClose: true,
      //     message: "商品规格必须大于1，否则请直接到菜单“吧台”中，进行“上架操作”。",
      //     type: "error",
      //     duration: 3000
      //   });
      //   return;
      // }
  console.log(this.modeType)
      let doAddStandard = () => {
        this.$http({
          url: "/add-capacity",
          method: "POST",
          data: {
            id: item.id,
            storeId: item.storeId,
            productId: item.productId,
            name: item.name,
            unitId: item.unitId,
            mold: this.modeType,
            capacity: this.standard
          }
        }).then(res => {
          console.log(res);
          if (res.status === 200) {
            this.$message({
              message: "添加成功",
              type: "success",
              showClose: true,
              duration: 2000
            });
            this.showAddInp = false;
            this.standard = "";
            this.getStandardList(item);
            // 添成功后获取搜索结果列表
            // this.getProduct(this.searchItem, true);
            let newItem = {
              id: item.productId
            };
            if(this.modeType == "MATERIAL"){
              this.getMaterial(newItem,true);
            }else{
              this.getProduct(newItem, true);
            }
            
          }
        });
      };
      if (!this.standard) {
        this.$message({
          showClose: true,
          message: "请输入规格",
          type: "error"
        });
      } else {
        if (!/^[1-9][0-9]*$/.test(this.standard)) {
          // if(this.standard === '0'){
          // 	doAddStandard();
          // 	return;
          // }
          this.$message({
            showClose: true,
            message: "输入规格有误",
            type: "error"
          });
        } else {
          doAddStandard();
        }
      }
    },
    // 删除规格
    delStandard(item, itemForProduct) {
      this.isDel = true;
      this.modifyCapItemForDel = itemForProduct;
      this.$confirm("确认删除此规格？", "删除规格", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$http({
          url: "delete-invId",
          method: "GET",
          params: {
            invId: item.id
          }
        }).then(res => {
          if (res.status === 200) {
            if (res.data.code === 400) {
              this.$message({
                showClose: true,
                message: res.data.msg,
                type: "error",
                duration: 2000
              });
              return;
            }
            if (res.data.code === 200) {
              this.$message({
                showClose: true,
                message: "删除成功",
                type: "success"
              });
              this.getStandardList(itemForProduct);
              // 删除成功后获取搜索结果列表
              // let flag = true;//判断是否应该添加到当前首页数组
              // this.homeArr.map((item,index)=>{
              //   if(item.productId === this.searchItem.productId){
              //     flag = false;//为false时应该删除当前数组中的相应条目，然后再次重新获取，再次添加在首页数组
              //     //this.homeArr.splice()
              //   }
              // });
              // if(!flag){
              //   //
              //   this.$http({
              //     url: "get/product",
              //     method: "GET",
              //     params: {
              //       id: item.id,
              //       bat: "",
              //       index: ""
              //     }
              //   }).then(res => {
              //     this.keyWords = "";
              //     console.log(res);
              //     if (res.data.status === "false") {
              //       // 没有规格调出添加规格
              //       this.doShowFirst = true;
              //       this.$message({
              //         showClose: true,
              //         message: "当前商品无规格，请先添加规格",
              //         type: "error"
              //       });
              //       return;
              //     }
              //     let data = res.data;

              //     // this.homeArr = [];
              //     // for (var i = 0; i < data.length; i++) {
              //     // 	let obj = {
              //     // 		isPrice:false,//价格是否处于修改状态
              //     // 		id:data[i].id,
              //     // 		name:data[i].name,
              //     // 		productId:data[i].productId,
              //     // 		storeId:data[i].storeId,
              //     // 		capacity:data[i].capacity,//规格
              //     // 		purchasePrice:data[i].purchasePrice,//每件进价
              //     // 		quantity:data[i].quantity,//仓库库存,
              //     // 		whole:0
              //     // 	};
              //     let obj = {
              //       isPrice: false, //价格是否处于修改状态
              //       id: data.id,
              //       name: data.name,
              //       productId: data.productId,
              //       storeId: data.storeId,
              //       capacity: data.capacity, //规格
              //       purchasePrice: data.purchasePrice, //每件进价
              //       quantity: data.quantity, //仓库库存,
              //       whole: 0
              //     };
              //     this.homeArr.push(obj);
              //     // }
              //     // this.total = res.data.totalElements;
              //   });
              //   //
              // }
              // this.getProduct(this.searchItem, true);
              let newItem = {
                id: itemForProduct.productId
              };
              if(this.modeType == "MATERIAL"){
                this.getMaterial(newItem,true);
              }else{
                this.getProduct(newItem, true);
              }
              
              
              // //判断当前商品是否还有规格
              // this.$http({
              //   url: "/find-capacity",
              //   method: "GET",
              //   params: {
              //     productId: itemForProduct.productId,
              //     storeId: this.storeId
              //   }
              // }).then(res => {
              //   console.log('l')
              //   console.log(res)
              //   if(res.data.length < 1 || res.data === []){
              //     // let homeArr = this.homeArr;
              //     // this.homeArr.forEach((ele,index)=>{
              //     //      this.homeArr.splice(index,1);
              //     // })
              //     // // this.homeArr = homeArr;
              //     // console.log(this.homeArr)
              //     this.doShowFirst = false;
              //   }
              // });
              // this.modifyCapItemForDel = null;
              // this.searchItem = null;
            }
          }
        });
      });
      console.log(itemForProduct);
      console.log(item);
    },
    //获取批量数据
    getBatchData() {
      if (!this.preventBtn) {
        return;
      }
      this.preventBtn = false;
      this.homeArr = [];
      this.$http
        .get(this.storeId + "/homePage?page=0&size=10000")
        .then(res => {
          let data = res.data.products;
          for (var i = 0; i < data.length; i++) {
            let obj = {
              isStock: false, //规格是否处于修改状态
              isPrice: false, //价格是否处于修改状态
              whole: 0,
              single: 0,
              id: data[i].id,
              name: data[i].name,
              counterQuantity: data[i].counterQuantity, //吧台数量
              stockPrice: data[i].stockPrice / 100, //每件价格
              stockQuantityRatio: data[i].stockQuantityRatio, //规格
              typeName: data[i].typeName, //分类
              warehouseQuantity: data[i].warehouseQuantity, //仓库库存
            };
            this.homeArr.push(obj);
          }
          setTimeout(() => {
            this.preventBtn = true;
          }, 500);
        })
        .catch(err => {
          setTimeout(() => {
            this.preventBtn = true;
          }, 500);
        });
    },
    //警告修改规格
    willModify(ind) {
      this.homeArr[ind].isStock = true;
    },
    //修改规格 和 价格
    modify(item, ind, boo) {
      if (boo == "stock") {
        //修改规格
        if (!/^[1-9]\d*$/.test(item.stockQuantityRatio)) {
          this.$message({
            showClose: true,
            message: item.name + " 规格有误",
            type: "error"
          });
          return true;
        }
        this.$alert(
          "商品规格修改为：" + item.stockQuantityRatio + "，建议新建商品！",
          "确认修改",
          {
            confirmButtonText: "提交"
            // cancelButtonText: '去修改',
            // type: 'error'
          }
        )
          .then(() => {
            this.$http
              .post("/modify-format", {
                productId: item.id,
                stockQuantityRatio: parseInt(item.stockQuantityRatio)
              })
              .then(res => {
                this.homeArr[ind].isStock = false;
                this.$message({
                  showClose: true,
                  message: "修改成功",
                  type: "success"
                });
              });
          })
          .catch(() => {
            this.homeArr[ind].isStock = false;
          });
      } else if (boo == "price") {
        //修改价格
        if (!/^(0|[1-9][0-9]{0,9})(\.[0-9]{1,2})?$/.test(item.purchasePrice)) {
          this.$message({
            showClose: true,
            message: item.name + " 每件价格有误",
            type: "error"
          });
          return true;
        }
        this.$http
          .post("/update", {
            id: item.id,
            price: parseFloat(item.purchasePrice)
          })
          .then(res => {
            console.log(res);
            this.homeArr[ind].isPrice = false;
            this.$message({
              showClose: true,
              message: "修改成功",
              type: "success"
            });
          });
      }
    },
    //删除某个商品
    del(item, ind) {
      this.$confirm(`是否确认 ${item.name} 不入库`, "是否入库", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.homeArr.splice(ind, 1);
      });
    },
    //根据id获取某个商品
    getSearchItem(item) {
      this.doShowAddInp();
      this.searchItem = item;
      console.log(item);
      for (var i = 0; i < this.homeArr.length; i++) {
        if (this.homeArr[i].productId == item.id) {
          this.$message({
            showClose: true,
            message: "请勿重复添加",
            type: "error"
          });
          return;
        }
      }
      // this.$http.get(this.storeId+'/stock/product-search?productId='+item.id).then((res)=>{
      // 	this.keyWords = '';
      // 	let obj = {
      // 		isStock:false,//规格是否处于修改状态
      // 		isPrice:false,//价格是否处于修改状态
      // 		id:res.data.id,
      // 		name:res.data.name,
      // 		whole: 0,
      // 		single: 0,
      // 		stockPrice:res.data.stockPrice/100,
      // 		typeName:res.data.typeName,
      // 		stockQuantityRatio:res.data.stockQuantityRatio,
      // 		warehouseQuantity:res.data.warehouseQuantity,
      // 		counterQuantity:res.data.counterQuantity
      // 	};
      // 	this.homeArr.push(obj);
      // })
      console.log(this.modeType)
      if(this.modeType == "PRODUCT"){
        this.getProduct(item);
      }else{
        this.getMaterial(item);
      }
    },
    getMaterial(item, isNull = false) {
      if (isNull) {
        this.$http({
          url: "get/material",
          method: "GET",
          params: {
            id: item.id,
          }
        }).then(res => {
          this.keyWords = "";
          console.log(res);
          if (res.data.status === "false") {
            if(this.isDel){
              this.homeArr = [];
              this.isDel = false;
            }else{
              this.doShowFirst = true;
              this.$message({
                showClose: true,
                message: "当前原料无规格，请先添加规格",
                type: "error"
              });
              console.log(this.doShowFirst);
            }
            return;
          }
          let data = res.data;

          this.homeArr = [];
          let obj = {
            isPrice: false, //价格是否处于修改状态
            id: data.id,
            name: data.name,
            productId: data.productId,
            storeId: data.storeId,
            capacity: data.capacity, //规格
            purchasePrice: data.purchasePrice, //每件进价
            quantity: data.quantity, //仓库库存,
            unitName: data.unitName, 
            unitId: data.unitId, 
            whole: 0
          };
          this.homeArr.push(obj);
          // this.total = res.data.totalElements;
        });
      } else {
        this.$http({
          url: "get/material",
          method: "GET",
          params: {
            id: item.id,
            bat: "",
            index: ""
          }
        }).then(res => {
          this.keyWords = "";
          console.log(res);
          if (res.data.status === "false") { 
            // 没有规格调出添加规格
            if(this.isDel){
              this.homeArr = [];
              this.isDel = false;
            }else{
              this.doShowFirst = true;
              this.$message({
                showClose: true,
                message: "当前原料无规格，请先添加规格",
                type: "error"
              });
              console.log(this.doShowFirst);
            }
            return;
          }
          let data = res.data;
          let obj = {
            isPrice: false, //价格是否处于修改状态
            id: data.id,
            name: data.name,
            productId: data.productId,
            storeId: data.storeId,
            capacity: data.capacity, //规格
            purchasePrice: data.purchasePrice, //每件进价
            quantity: data.quantity, //仓库库存,
            unitName: data.unitName, 
            unitId: data.unitId, 
            whole: 0
          };
          this.homeArr.push(obj);
        });
      }
    },
    // isNull用来判断当前是否应该置空homeArr数组
    getProduct(item, isNull = false) {
      if (isNull) {
        this.$http({
          url: "get/product",
          method: "GET",
          params: {
            id: item.id,
            mold:this.modeType,
            bat: "",
            index: ""
          }
        }).then(res => {
          this.keyWords = "";
          console.log(res);
          if (res.data.status === "false") {
            // 没有规格调出添加规格
            // this.doShowFirst = true;
            // this.$message({
            //   showClose: true,
            //   message: "当前商品无规格，请先添加规格",
            //   type: "error"
            // });
            // console.log(this.doShowFirst);
            if(this.isDel){
              this.homeArr = [];
              this.isDel = false;
            }else{
              this.doShowFirst = true;
              this.$message({
                showClose: true,
                message: "当前商品无规格，请先添加规格",
                type: "error"
              });
              console.log(this.doShowFirst);
            }
            return;
          }
          let data = res.data;

          this.homeArr = [];
          // for (var i = 0; i < data.length; i++) {
          // 	let obj = {
          // 		isPrice:false,//价格是否处于修改状态
          // 		id:data[i].id,
          // 		name:data[i].name,
          // 		productId:data[i].productId,
          // 		storeId:data[i].storeId,
          // 		capacity:data[i].capacity,//规格
          // 		purchasePrice:data[i].purchasePrice,//每件进价
          // 		quantity:data[i].quantity,//仓库库存,
          // 		whole:0
          // 	};
          // 	this.homeArr.push(obj);
          // }
          let obj = {
            isPrice: false, //价格是否处于修改状态
            id: data.id,
            name: data.name,
            productId: data.productId,
            storeId: data.storeId,
            capacity: data.capacity, //规格
            purchasePrice: data.purchasePrice, //每件进价
            quantity: data.quantity, //仓库库存,
            whole: 0
          };
          this.homeArr.push(obj);
          // this.total = res.data.totalElements;
        });
      } else {
        this.$http({
          url: "get/product",
          method: "GET",
          params: {
            id: item.id,
            mold:this.modeType,
            bat: "",
            index: ""
          }
        }).then(res => {
          this.keyWords = "";
          console.log(res);
          if (res.data.status === "false") { 
            // 没有规格调出添加规格
            if(this.isDel){
              this.homeArr = [];
              this.isDel = false;
            }else{
              this.doShowFirst = true;
              this.$message({
                showClose: true,
                message: "当前商品无规格，请先添加规格",
                type: "error"
              });
              console.log(this.doShowFirst);
            }
            return;
          }
          let data = res.data;

          // this.homeArr = [];
          // for (var i = 0; i < data.length; i++) {
          // 	let obj = {
          // 		isPrice:false,//价格是否处于修改状态
          // 		id:data[i].id,
          // 		name:data[i].name,
          // 		productId:data[i].productId,
          // 		storeId:data[i].storeId,
          // 		capacity:data[i].capacity,//规格
          // 		purchasePrice:data[i].purchasePrice,//每件进价
          // 		quantity:data[i].quantity,//仓库库存,
          // 		whole:0
          // 	};
          let obj = {
            isPrice: false, //价格是否处于修改状态
            id: data.id,
            name: data.name,
            productId: data.productId,
            storeId: data.storeId,
            capacity: data.capacity, //规格
            purchasePrice: data.purchasePrice, //每件进价
            quantity: data.quantity, //仓库库存,
            whole: 0
          };
          this.homeArr.push(obj);
          // }
          // this.total = res.data.totalElements;
        });
      }
    },
    willUp() {
      this.doShowAddInp();
      let kind = 0;
      if (this.homeArr.length == 0) {
        this.$message({
          showClose: true,
          message: "请选择商品",
          type: "error"
        });
        return;
      } else {
        for (var i = 0; i < this.homeArr.length; i++) {
          if (/^0{1,}\d+$/.test(this.homeArr[i].whole)) {
            this.$message({
              showClose: true,
              message: "请输入正确的  " + this.homeArr[i].name + "  商品数量",
              type: "error"
            });
            return;
          }
          if (!/^\d+$/.test(this.homeArr[i].whole)) {
            this.$message({
              showClose: true,
              message: "请输入正确的  " + this.homeArr[i].name + "  商品数量",
              type: "error"
            });
            return;
          }
          if (this.homeArr[i].whole !== 0) {
            kind++;
          }
          // if(!/^\d+$/.test(this.homeArr[i].single)){
          // 	this.$message({
          // 		showClose: true,
          //         message: '请输入正确的  '+this.homeArr[i].name+'  商品个数',
          //         type: 'error'
          //     })
          //     return;
          // }
        }
      }
      this.dialogBtn = true;
      this.billData = {
        typeValue: "PURCHASE_IN",
        notes: "",
        totalAmount: "",
        imgUrl: "",
        printNum: 1,
        isPrint: false,
        kind: kind
      };
    },
    //提交数据
    stockUp() {
      if (this.billData.totalAmount !== "") {
        if (
          !/^(0|[1-9][0-9]{0,9})(\.[0-9]{1,2})?$/.test(
            this.billData.totalAmount
          )
        ) {
          this.$message({
            showClose: true,
            message: "总金额格式有误",
            type: "error",
            duration: 2000
          });
          return;
        }
        if (!/^\d{0,9}$/.test(parseFloat(this.billData.totalAmount) * 100)) {
          this.$message({
            showClose: true,
            message: "总金额格式有误",
            type: "error"
          });
          return;
        }
      }
      if (!this.billData.typeValue) {
        this.$message({
          showClose: true,
          message: "请选择入库原因",
          type: "error"
        });
        return;
      }
      if (!this.preventBtn) {
        return;
      }
      this.preventBtn = false;
      // let body = {
      // 	single:0,
      // 	whole:0,
      // 	id:this.$uuid(),
      // 	storeId:this.storeId,
      // 	notes:this.billData.notes,
      // 	stockSource:this.billData.typeValue,
      // 	totalAmount:parseFloat(this.billData.totalAmount)*100,
      // 	bill:this.billData.imgUrl,
      // 	source:'WAREHOUSE',
      // 	inventores:[]
      // }
      let store = JSON.parse(sessionStorage.getItem("store"));
      let body = {
        operatorId: store.employeeId,
        operatorName: store.employeeName,
        code: this.$uuid(),
        storeId: this.storeId,
        notes: this.billData.notes,
        stockSource: this.billData.typeValue,
        totalAmount: parseFloat(this.billData.totalAmount),
        countNum: 0,
        inventores: [],
        mold:this.modeType
      };
      for (var i = 0; i < this.homeArr.length; i++) {
        if (this.homeArr[i].whole !== 0) {
          let newInventores = {
            invId: this.homeArr[i].id,
            productName: this.homeArr[i].name,
            productId: this.homeArr[i].productId,
            quantity: this.homeArr[i].whole,
            capacity: this.homeArr[i].capacity
          };
          body.countNum += parseInt(this.homeArr[i].whole);
          // body.single+=parseInt(this.homeArr[i].single);
          body.inventores.push(newInventores);
        }
      }

      this.$http
        .post("/stock-in", body)
        .then(res => {
          console.log(res);
          if (res.data.code === 200) {
            this.$message({
              showClose: true,
              message: "操作成功",
              type: "success"
            });
          } else if (res.data.code === 400) {
            this.$message({
              showClose: true,
              message: res.data.msg,
              type: "error"
            });
            setTimeout(() => {
              this.preventBtn = true;
            }, 1000);
            return;
          } else if (res.data.code === 500) {
            this.$message({
              showClose: true,
              message: "系统错误",
              type: "error"
            });
            setTimeout(() => {
              this.preventBtn = true;
            }, 1000);
            return;
          }

          // 打印暂时取消
          // if(this.billData.isPrint){
          // 	this.$posPrint(this.billData.printNum, document.getElementById("print").innerHTML);
          // }
          this.homeArr = [];
          this.dialogBtn = false;
          setTimeout(() => {
            this.preventBtn = true;
          }, 1000);
        })
        .catch(err => {
          setTimeout(() => {
            this.preventBtn = true;
          }, 1000);
        });
    },
    //选择图片
    coverImg: function(e) {
      let reader = new FileReader();
      let that = this;
      let fileObj = e.target.files[0];

      if (e.target.files.length == 0) {
        return false;
      }
      // 判断图片大小
      if (fileObj.size > this.coverImgMaxSize) {
        this.errorMsg = "上传图片的大小不能超过5MB";
        this.openErrorTip = true;
        this.$message({
          showClose: true,
          message: "上传图片的大小不能超过5MB",
          type: "error"
        });
        return false;
      }
      reader.onload = (function(file) {
        return function(e) {
          let that2 = this; // 缓存当前this
          let img = new Image();
          img.src = this.result;
          img.onload = function() {
            let imgBase64 = that2.result; //获得图片的base64的数据

            // 判断是否是移动端设备
            let sUserAgent = navigator.userAgent.toLowerCase();
            let bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
            let bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
            let bIsMidp = sUserAgent.match(/midp/i) == "midp";
            let bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
            let bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
            let bIsAndroid = sUserAgent.match(/android/i) == "android";
            let bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
            let bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
            if (
              bIsIpad ||
              bIsIphoneOs ||
              bIsMidp ||
              bIsUc7 ||
              bIsUc ||
              bIsAndroid ||
              bIsCE ||
              bIsWM
            ) {
              that.mobileUploadImg(imgBase64);
            } else {
              that.oldImgBase64 = imgBase64;
              that.showCrop = true;
            }
          };
          $(".pcImgFile").val("");
        };
      })(e.target.files[0]);
      reader.readAsDataURL(e.target.files[0]);
    },
    // 移动端上传图片
    mobileUploadImg: function(imgBase64) {
      this.infoload = true;
      this.$http
        .post(
          API_BASE_URL+"v1/image/json/upload?storeId=" +
            this.storeId,
          { file: imgBase64 }
        )
        .then(res => {
          this.billData.imgUrl = imgUrl;
          this.infoload = false;
        })
        .catch(() => {
          this.infoload = false;
        });
    },
    // 获得裁剪后图片base64
    getCropImgBase: function(imgUrl) {
      this.billData.imgUrl = imgUrl;
    }
  },
  created() {
    try {
      if(this.$route.query.queryModeType){
        this.homeArr = [];
        this.modeType = this.$route.query.queryModeType;
      }
    } catch (error) {
      
    }
  },
  mounted() {},
  beforeDestroy() {}
};
</script>
<style lang="scss" scoped>
@import "../../../../static/css/common.scss";
@import "inner";
</style>